package com.siteseat.common.security;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

import com.siteseat.common.misc.IOHelper;


/**
 * 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类. 支持Hex与Base64两种编码方式.
 */
public class CryptoHelper {

  private static final String DES                      = "DES";

  private static final String AES                      = "AES";

  private static final String HMACSHA1                 = "HmacSHA1";

  public static final int     DEFAULT_HMACSHA1_KEYSIZE = 160;        // RFC2401

  public static final int     DEFAULT_AES_KEYSIZE      = 128;
  

  /**
   * 
   *
   * @param userName
   * @param password
   * @param salt
   * @return
   * @throws UnsupportedEncodingException
   */
  public static String crudeEncrypt( String userName, String password, String clientId, long salt ) throws SecurityException {
    String toEncrypt = "" + salt + "/" + userName + "/" + password + "/" + clientId;
    byte[] aesKey = Arrays.copyOf( String.format( "%s", password ).getBytes(IOHelper.CHARSET), 16 );
    return aesEncryptToBase64( toEncrypt, aesKey );
  }
  
  /**
   * 
   *
   * @param userName
   * @param password
   * @param toDecrypt
   * @param lastSalt
   * @return
   * @throws UnsupportedEncodingException
   */
  public static Long crudeVerify( String userName, String password, String toDecrypt, String clientId, long lastSalt ) throws SecurityException {
    byte[] aesKey = Arrays.copyOf( String.format( "%s", password ).getBytes(IOHelper.CHARSET), 16 );
    
    String decrypted = aesDecryptFromBase64( toDecrypt, aesKey);
    
    String[] splitted = decrypted.split( "/" );
    if( splitted.length != 4 ) {
      throw new SecurityException( "Invalid cryption: " + decrypted );
    }
    
    long newSalt;
    try {
      newSalt = Long.parseLong( splitted[0] );
    }catch( NumberFormatException e ) {
      throw new SecurityException( "Invalid cryption salt: " + decrypted );
    }
    
    if( lastSalt > 0 && newSalt <= lastSalt ) {
      throw new SecurityException( "Duplicated cryption salt: " + decrypted );
    }
    
    if( userName.equals( splitted[1] ) == false ) {
      throw new SecurityException( "Invalid user name: " + decrypted );
    }
    
    if( password.equals( splitted[2] ) == false ) {
      throw new SecurityException( "Invalid password: " + decrypted );
    }
    
    if( clientId.equals( splitted[3] ) == false ) {
      throw new SecurityException( "Invalid client id: " + decrypted );
    }
    
    return Long.valueOf(newSalt);
  }
  
  // -- HMAC-SHA1 funciton --//
  /**
   * 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
   * 
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          HMAC-SHA1密钥
   * @return 签名了的字节数组
   * @throws SecurityException 
   */
  public static byte[] hmacSha1( String input, byte[] keyBytes ) throws SecurityException {
    try {
      SecretKey secretKey = new SecretKeySpec( keyBytes, HMACSHA1 );
      Mac mac = Mac.getInstance( HMACSHA1 );
      mac.init( secretKey );
      return mac.doFinal( input.getBytes() );
    } catch( Exception e ) {
      throw new SecurityException( e );
    }
  }

  /**
   * 使用HMAC-SHA1进行消息签名, 返回Hex编码的结果,长度为40字符.
   * 
   * @param input
   * @param keyBytes
   * @return 签名并编码后的文本
   * @throws SecurityException 
   * @see #hmacSha1(String, byte[])
   */
  public static String hmacSha1ToHex( String input, byte[] keyBytes ) throws SecurityException {
    byte[] macResult = hmacSha1( input, keyBytes );
    return EncodeHelper.hexEncode( macResult );
  }

  /**
   * 使用HMAC-SHA1进行消息签名, 返回Base64编码的结果.
   * 
   * @param input
   * @param keyBytes
   * @return 签名并编码后的文本
   * @throws SecurityException 
   * @see #hmacSha1(String, byte[])
   */
  public static String hmacSha1ToBase64( String input, byte[] keyBytes ) throws SecurityException {
    byte[] macResult = hmacSha1( input, keyBytes );
    return EncodeHelper.base64Encode( macResult );
  }

  /**
   * 使用HMAC-SHA1进行消息签名, 返回Base64编码的URL安全的结果.
   * 
   * @param input
   * @param keyBytes
   * @return 签名并编码后的文本
   * @see #hmacSha1(String, byte[])
   */
  /*
   * public static String hmacSha1ToBase64UrlSafe(String input, byte[] keyBytes)
   * { byte[] macResult = hmacSha1(input, keyBytes); return
   * EncodeUtils.base64UrlSafeEncode(macResult); }
   */

  /**
   * 校验Hex编码的HMAC-SHA1签名是否正确.
   * 
   * @param hexMac
   *          Hex编码的签名
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          密钥
   * @return 如果签名正确，返回true
   * @throws SecurityException 
   */
  public static boolean isHexMacValid( String hexMac, String input, byte[] keyBytes ) throws SecurityException {
    byte[] expected = EncodeHelper.hexDecode( hexMac );
    byte[] actual = hmacSha1( input, keyBytes );

    return Arrays.equals( expected, actual );
  }

  /**
   * 校验Base64/Base64URLSafe编码的HMAC-SHA1签名是否正确.
   * 
   * @param base64Mac
   *          Base64/Base64URLSafe编码的签名
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          密钥
   * @return 如果签名正确，返回true
   */
  /*
   * public static boolean isBase64MacValid(String base64Mac, String input,
   * byte[] keyBytes) { byte[] expected = EncodeUtils.base64Decode(base64Mac);
   * byte[] actual = hmacSha1(input, keyBytes); return Arrays.equals(expected,
   * actual); }
   */

  /**
   * 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节). HMAC-SHA1算法对密钥无特殊要求,
   * RFC2401建议最少长度为160位(20字节).
   * 
   * @return HMAC-SHA1密钥的字节数组
   * @throws SecurityException 
   */
  public static byte[] generateMacSha1Key() throws SecurityException {
    try {
      KeyGenerator keyGenerator = KeyGenerator.getInstance( HMACSHA1 );
      keyGenerator.init( DEFAULT_HMACSHA1_KEYSIZE );
      SecretKey secretKey = keyGenerator.generateKey();
      return secretKey.getEncoded();
    } catch( Exception e ) {
      throw new SecurityException( e );
    }
  }

  /**
   * 生成HMAC-SHA1密钥, 返回Hex编码的结果,长度为40字符.
   * 
   * @return HMAC-SHA1密钥的文本
   * @throws SecurityException 
   * @see #generateMacSha1Key()
   */
  public static String generateMacSha1HexKey() throws SecurityException {
    return EncodeHelper.hexEncode( generateMacSha1Key() );
  }

  // -- DES function --//
  /**
   * 使用DES加密原始字符串, 返回Hex编码的结果.
   * 
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          符合DES要求的密钥
   * @return 加密并编码了的文本
   * @throws SecurityException 
   */
  public static String desEncryptToHex( String input, byte[] keyBytes ) throws SecurityException {
    byte[] encryptResult = des( input.getBytes(), keyBytes, Cipher.ENCRYPT_MODE );
    return EncodeHelper.hexEncode( encryptResult );
  }

  /**
   * 使用DES加密原始字符串, 返回Base64编码的结果.
   * 
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          符合DES要求的密钥
   * @return 加密并编码了的文本
   * @throws SecurityException 
   */
  public static String desEncryptToBase64( String input, byte[] keyBytes ) throws SecurityException {
    byte[] encryptResult = des( input.getBytes(), keyBytes, Cipher.ENCRYPT_MODE );
    return EncodeHelper.base64Encode( encryptResult );
  }
  

  /**
   * 使用AES解密Base64编码的加密字符串, 返回原始字符串.
   * 
   * @param input
   *          Base64编码的加密字符串
   * @param keyBytes
   *          符合AES要求的密钥
   * @return 原始字符串
   * @throws UnsupportedEncodingException 
   */
  
  public static String aesDecryptFromBase64(String input, byte[] keyBytes) throws SecurityException {
    byte[] decryptResult = aes( EncodeHelper.base64Decode(input), keyBytes, Cipher.DECRYPT_MODE); 
    return new String(decryptResult, IOHelper.CHARSET );
  }
  

  /**
   * 使用DES解密Hex编码的加密字符串, 返回原始字符串.
   * 
   * @param input
   *          Hex编码的加密字符串
   * @param keyBytes
   *          符合DES要求的密钥
   * @return 原始字符串
   * @throws UnsupportedEncodingException 
   */
  public static String desDecryptFromHex( String input, byte[] keyBytes ) throws SecurityException {
    byte[] decryptResult = des( EncodeHelper.hexDecode( input ), keyBytes, Cipher.DECRYPT_MODE );
    return new String( decryptResult, IOHelper.CHARSET );
  }

  /**
   * 使用DES解密Base64编码的加密字符串, 返回原始字符串.
   * 
   * @param input
   *          Base64编码的加密字符串
   * @param keyBytes
   *          符合DES要求的密钥
   * @return 原始字符串
   */
  /*
   * public static String desDecryptFromBase64(String input, byte[] keyBytes) {
   * byte[] decryptResult = des(EncodeUtils.base64Decode(input), keyBytes,
   * Cipher.DECRYPT_MODE); return new String(decryptResult, IOHelper.CHARSET ); }
   */

  /**
   * 使用DES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
   * 
   * @param inputBytes
   *          原始字节数组
   * @param keyBytes
   *          符合DES要求的密钥
   * @param mode
   *          Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
   * @throws SecurityException 
   */
  private static byte[] des( byte[] inputBytes, byte[] keyBytes, int mode ) throws SecurityException {
    try {
      DESKeySpec desKeySpec = new DESKeySpec( keyBytes );
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance( DES );
      SecretKey secretKey = keyFactory.generateSecret( desKeySpec );

      Cipher cipher = Cipher.getInstance( DES );
      cipher.init( mode, secretKey );
      return cipher.doFinal( inputBytes );
    } catch( Exception e ) {
      throw new SecurityException( e );
    }
  }

  /**
   * 生成符合DES要求的密钥, 长度为64位(8字节).
   * 
   * @return 密钥
   * @throws SecurityException 
   */
  public static byte[] generateDesKey() throws SecurityException {
    try {
      KeyGenerator keyGenerator = KeyGenerator.getInstance( DES );
      SecretKey secretKey = keyGenerator.generateKey();
      return secretKey.getEncoded();
    } catch( Exception e ) {
      throw new SecurityException( e );
    }
  }

  /**
   * 生成符合DES要求的Hex编码密钥, 长度为16字符.
   * 
   * @return 密钥
   * @throws SecurityException 
   */
  public static String generateDesHexKey() throws SecurityException {
    return EncodeHelper.hexEncode( generateDesKey() );
  }

  // -- AES funciton --//
  /**
   * 使用AES加密原始字符串, 返回Hex编码的结果.
   * 
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          符合AES要求的密钥
   * @return 加密并编码了的字符串
   * @throws SecurityException 
   */
  public static String aesEncryptToHex( String input, byte[] keyBytes ) throws SecurityException {
    byte[] encryptResult = aes( input.getBytes(), keyBytes, Cipher.ENCRYPT_MODE );
    return EncodeHelper.hexEncode( encryptResult );
  }

  /**
   * 使用AES加密原始字符串, 返回Base64编码的结果.
   * 
   * @param input
   *          原始输入字符串
   * @param keyBytes
   *          符合AES要求的密钥
   * @return 加密并编码了的字符串
   * @throws SecurityException 
   */
  public static String aesEncryptToBase64( String input, byte[] keyBytes ) throws SecurityException {
    byte[] encryptResult = aes( input.getBytes(), keyBytes, Cipher.ENCRYPT_MODE );
    return EncodeHelper.base64Encode( encryptResult );
  }

  /**
   * @param input
   * @param keyBytes
   * @return
   * @throws SecurityException 
   */
  public static byte[] aesEncrypt( byte[] inputBytes, byte[] keyBytes ) throws SecurityException {
    return aes( inputBytes, keyBytes, Cipher.ENCRYPT_MODE );
  }

  /**
   * @param input
   * @param keyBytes
   * @return
   * @throws SecurityException 
   */
  public static byte[] aesDecrypt( byte[] inputBytes, byte[] keyBytes ) throws SecurityException {
    return aes( inputBytes, keyBytes, Cipher.DECRYPT_MODE );
  }

  /**
   * 使用AES解密Hex编码的加密字符串, 返回原始字符串.
   * 
   * @param input
   *          Hex编码的加密字符串
   * @param keyBytes
   *          符合AES要求的密钥
   * @return 原始字符串
   * @throws UnsupportedEncodingException 
   */
  public static String aesDecryptFromHex( String input, byte[] keyBytes ) throws SecurityException {
    byte[] decryptResult = aes( EncodeHelper.hexDecode( input ), keyBytes, Cipher.DECRYPT_MODE );
    return new String( decryptResult, IOHelper.CHARSET );
  }

  /**
   * 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
   * 
   * @param inputBytes
   *          原始字节数组
   * @param keyBytes
   *          符合AES要求的密钥
   * @param mode
   *          Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
   */
  private static byte[] aes( byte[] inputBytes, byte[] keyBytes, int mode ) throws SecurityException {
    try {
      SecretKey secretKey = new SecretKeySpec( keyBytes, AES );
      Cipher cipher = Cipher.getInstance( AES );
      cipher.init( mode, secretKey );
      return cipher.doFinal( inputBytes );
    } catch( Exception e ) {
      throw new SecurityException( e );
    }
  }

  /**
   * 生成AES密钥,返回字节数组,长度为128位(16字节).
   * 
   * @return 密钥字节数组
   * @throws SecurityException 
   */
  public static byte[] generateAesKey() throws SecurityException {
    try {
      KeyGenerator keyGenerator = KeyGenerator.getInstance( AES );
      keyGenerator.init( DEFAULT_AES_KEYSIZE );
      SecretKey secretKey = keyGenerator.generateKey();
      return secretKey.getEncoded();
    } catch( Exception e ) {
      throw new SecurityException( e );
    }
  }

  /**
   * 生成AES密钥, 返回Hex编码的结果,长度为32字符.
   * 
   * @return 密钥文本
   * @throws SecurityException 
   * @see #generateMacSha1Key()
   */
  public static String generateAesHexKey() throws SecurityException {
    return EncodeHelper.hexEncode( generateAesKey() );
  }

}
